package cn.enilu.itnews.utils;

import com.google.common.base.Charsets;
import com.google.common.io.Files;
import com.google.common.io.Resources;
import org.apache.commons.lang.StringUtils;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.net.URL;
import java.util.Map;
import java.util.HashMap;

/**
 * Created by zhangxue on 2015/10/23.
 */
public class VelocityUtils {


    public static String getTemplateContents(URL templatePath,Map<String,Object> parameters){
        try{
            VelocityContext context = new VelocityContext();
            if(!parameters.isEmpty()){
                for(String key:parameters.keySet()){
                    context.put(key,parameters.get(key));
                }
            }
            StringWriter writer = new StringWriter();
            //URL url = Resources.getResource(templatePath);
            String template = Resources.toString(templatePath, Charsets.UTF_8);

            VelocityEngine engine = new VelocityEngine();
            engine.setProperty("runtime.references.strict", false);
            engine.init();
            engine.evaluate(context, writer, "", template);
            return writer.toString();
        }catch (Exception e){
            e.printStackTrace();
        }

       return null;

    }

    public static void main(String[] args) throws IOException {
        URL templates = Class.class.getResource("/test.vm");
        Map data = new HashMap<String,Object>();
        data.put("name","张雪");

        String contents = getTemplateContents(templates,data);
        if(StringUtils.isNotBlank(contents)){
            File file = new File("test.txt");
            if(!file.exists()){
                file.createNewFile();
                //file.getParentFile().mkdirs();
                Files.write(contents.getBytes(Charsets.UTF_8), file);
            }else{
                Files.write(contents.getBytes(Charsets.UTF_8), file);
            }
        }
    }
}
